<template>
	<view class="dict-warp">
		<uni-data-select :disabled="disabled" :placeholder="placeholder" v-bind="$attrs" :multiple="multiple" v-model="dictValue" :localdata="options">
		</uni-data-select>
	</view>
</template>

<script>
	import { getDict } from '@/api/system/common.js'
	export default {
		name: 'DictSelect',
		props: {
			dictCode: String,
			value: [String,Number],
			placeholder:{
				type:String,
				default:'请选择'
			},
			disabled:Boolean,
			multiple:Boolean
		},
		watch: {
			value: {
				handler(val) {
					if(this.multiple){
						this.dictValue = val.split(',')
					}else{
						this.dictValue = val
					}
				},
				immediate:true
			}
		},
		data() {
			return {
				options: [],
				dictValue: null
			}
		},
		methods: {
			async initData() {
				return getDict(this.dictCode).then(res => {
					if (res.data.success) {
						const items = res.data.result?.items || []
						items.sort((a, b) => {
							return a.itemSort - b.itemSort
						})
						this.options = items.map(item => {
							return {
								text:item.itemText,
								value:item.itemValue
							}
						})
					}
				})
			},
			change(value){
				if(this.multiple){
					this.$emit('change', value?.join(','))
				}else{
					this.$emit('change', value)
				}	
			}
		},
		async created(){
			this.initData()
		},
		model: {
			prop: 'value',
			event: 'change'
		}
	}
</script>

<style lang="scss" scoped>
.dict-warp{
	width: 100%;
}
</style>